// 存储前缀变量
export const PREFIX = 'PORTFOLIO-'

// 16进制转换为RGBA
export function set16ToRgb(str, opcity = 1) {

  const reg = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/
  if (!reg.test(str)) {
    return
  }
  /* eslint-disable-next-line no-useless-escape  */
  let newStr = str.toLowerCase().replace(/\#/g, '')
  const len = newStr.length
  if (len === 3) {
    let t = ''
    for (let i = 0; i < len; i++) {
      t += newStr.slice(i, i + 1).concat(newStr.slice(i, i + 1))
    }
    newStr = t
  }
  const arr = [] // 将字符串分隔，两个两个的分隔
  for (let i = 0; i < 6; i += 2) {
    const s = newStr.slice(i, i + 2)
    arr.push(parseInt(`0x${s}`, 16))
  }
  return `rgba(${arr.join(',')}, ${opcity})`
}

// 分割数组
export function chunk(arr, size) {
  return Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  )
}

/**
 * 深拷贝对象
 * @param {*} obj - 需要深拷贝的对象
 * @param {WeakMap} hash - 用于处理循环引用的哈希表
 * @returns {*} 深拷贝后的对象
 */
export function deepClone(obj, hash = new WeakMap()) {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj)
  if (obj instanceof RegExp) return new RegExp(obj.source, obj.flags)
  if (obj instanceof HTMLElement) return obj.cloneNode(true)

  if (hash.has(obj)) return hash.get(obj)

  const clonedObj = Array.isArray(obj) ? [] : {}
  hash.set(obj, clonedObj)

  Object.keys(obj).forEach(key => {
    clonedObj[key] = deepClone(obj[key], hash)
  })

  return clonedObj
}

// 获取响应式尺寸
export function getResponsiveSize(basePx) {
  const baseWidth = 1920
  const currentWidth = document.documentElement.clientWidth
  return basePx * (currentWidth / baseWidth)
}

// 为路由添加ID
export function addIdsToRoutes(routes) {
  let idCounter = 1

  function assignIds(routeArray, parentId = '') {
    return routeArray.map((route, index) => {
      // 构建唯一ID，基于父级ID和当前索引
      const currentId = parentId ? `${parentId}${index + 1}` : `${idCounter++}`

      const newRoute = {
        ...route,
        id: parseInt(currentId)
      }

      // 如果有子路由，递归处理
      if (route.children) {
        newRoute.children = assignIds(route.children, currentId)
      }

      return newRoute
    })
  }

  return assignIds(routes)
}

/**
 * 将路由数据转换为适合 fuse.js 搜索的格式
 * 只包含最终可访问的菜单项（即叶子节点）
 * @param {Array} routes - 路由数组
 * @param {Array} parentTitles - 父级标题数组
 * @param {String} parentPath - 父级路径
 * @returns {Array} 转换后的数据数组
 */
export function transformRoutesForSearch(routes, parentTitles = [], parentPath = '') {
  const result = []

  routes.forEach(route => {
    // 正确构建完整路径，避免重复
    let fullPath = ''
    if (route.path.startsWith('/')) {
      fullPath = route.path
    } else {
      fullPath = parentPath + (parentPath.endsWith('/') ? '' : '/') + route.path
    }

    // 如果路由有 meta 和 title，则处理它
    if (route.meta && route.meta.title) {
      const currentTitles = [...parentTitles, route.meta.title]

      // 如果有子路由，递归处理（但不添加当前路由）
      if (route.children && route.children.length > 0) {
        result.push(...transformRoutesForSearch(route.children, currentTitles, fullPath))
      } else {
        // 如果没有子路由，说明是最终的菜单项，添加到结果中
        result.push({
          title: currentTitles,
          path: fullPath
        })
      }
    } else if (route.children) {
      // 即使当前路由没有标题，也要处理子路由
      result.push(...transformRoutesForSearch(route.children, parentTitles, parentPath))
    }
  })

  return result
}
